package cn.itcast.crm.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {
	
	private static final Logger log = Logger.getLogger(HandlerInterceptor.class);
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String userName = (String) request.getSession().getAttribute("LOGIN_USER");
        if (StringUtils.isEmpty(userName)) {
//            response.sendRedirect("/jsp/login.jsp");
        	request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
//            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/crm/jsp/";
//            log.debug("跳转指定的路径basePath:"+basePath);
//            response.sendRedirect(basePath+"login.jsp");
            log.debug("尚未登录，跳到登录页面");
            return false;
        }
        log.debug("已经登录，放行请求");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    	 log.debug("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    	 log.debug("afterCompletion");
    }

}